package com.client.utility;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON工具类
 */
public class JsonUtility {
	/**
	 * JSON字符串转成JsonNode
	 * @param json
	 * @return
	 */
	public static JsonNode toJsonNode(String json) {
		try{
			return objectMapper.readValue(json, JsonNode.class);
		}catch(IOException e) {
			return null;
		}
	}
	
	/**
	 * 将JSON格式的字符串转换成给定的实体类
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T StrToEntity(String json,Class<T> clazz) {
		try{
			return objectMapper.readValue(json, clazz);
		}catch(IOException e) {
			return null;
		}
	}
	
	/**
	 * 将实体类转换为JSON格式字符串
	 * @param source
	 * @return
	 */
	public static String entityToStr(Object source) {
		try {
			return objectMapper.writeValueAsString(source);
		} catch (JsonProcessingException e) {
			return null;
		}
	}
	
	/**
	 * 
	 * @param json
	 * @param dataType
	 * @param genericityTypes
	 * @return
	 */
	public static <T> T jsonToObject(String json,Class<?> dataType,Class<?>... genericityTypes) {
		JavaType type = objectMapper.getTypeFactory().constructParametricType(dataType, genericityTypes);
		try {
			return objectMapper.readValue(json,type);
		} catch (IOException e) {
			return null;
		}
	}
	
	public static Map<String,Object> strToMap(String json){
		try{
			return objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});
		}catch(IOException e) {
			return null;
		}
	}
	
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	static {
		// 在遇到未知属性的时候不抛出异常
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		//支持单引号
		objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
	}
}
